//
//  AppDelegate.m
//  ZhuanZuBao
//
//  Created by 戴伟 on 2020/8/28.
//  Copyright © 2020 戴伟. All rights reserved.
//

#import "AppDelegate.h"
#import "CYLTabBarControllerConfig.h"
#import "IQKeyboardManager.h"
#import <TencentOpenAPI/TencentOAuth.h>
#import <Bugly/Bugly.h>

@interface AppDelegate ()<CYLTabBarControllerDelegate, WXApiDelegate, TencentSessionDelegate>

@property (nonatomic, strong) TencentOAuth *oauth;

@end

@implementation AppDelegate



- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    
    if (@available(iOS 13.0, *)) {
        self.window.overrideUserInterfaceStyle = UIUserInterfaceStyleLight;
    }
//    appsecret：2b2207c7bade175d182afc9185a8240c
    [WXApi registerApp:@"wx2d157e5d72319a6f" universalLink:@"https://1234/"];
    
    
    _oauth = [[TencentOAuth alloc] initWithAppId:@"101906500" andUniversalLink:@"https://bktijb.jglinks.cn" andDelegate:self];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(needQQLogin) name:@"needQQLogin" object:nil];

    
    [IQKeyboardManager sharedManager].toolbarDoneBarButtonItemText = @"完成";
    
    [AMapServices sharedServices].apiKey = @"b69256e88b2d51086c4d7fc86debf3f1";
    
    [Bugly startWithAppId:@"ca696f331c"];
    
    User *user = [User sharedUser];
    WZLSERIALIZE_UNARCHIVE(user, @"User", userFilePath);
    CYLTabBarControllerConfig *config = [CYLTabBarControllerConfig new];
    config.tabBarController.delegate = self;
    [self.window setRootViewController:config.tabBarController];
    
    [self.window makeKeyWindow];
    
    return YES;
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{

    NSString *string =[url absoluteString];
    if ([string hasPrefix:@"wx2d157e5d72319a6f"]) {
        return  [WXApi handleOpenURL:url delegate:self];
    }
    return [TencentOAuth HandleOpenURL:url];
    return YES;
}
-(void)onResp:(BaseResp *)resp{
    if([resp isKindOfClass:[SendAuthResp class]]){
        SendAuthResp *aresp = (SendAuthResp *)resp;
        if (aresp.errCode != 0 ) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [MBProgressHUD showError:@"微信授权失败" toView:nil];
            });
            return;
        }
        //授权成功获取 OpenId
        NSString *code = aresp.code;
        [self getWeiXinOpenId:code];
    }else if([resp isKindOfClass:[SendMessageToWXResp class]]){
        SendMessageToWXResp *aresp = (SendMessageToWXResp *)resp;
        if (aresp.errCode != 0 ) {
            [MBProgressHUD showWarning:@"分享失败" toView:nil];
        }else{
            [MBProgressHUD showSuccess:@"分享成功" toView:nil];
        }
        return;
    }
}

//通过code获取access_token，openid，unionid
- (void)getWeiXinOpenId:(NSString *)code{
    /*
     appid    是    应用唯一标识，在微信开放平台提交应用审核通过后获得
     secret    是    应用密钥AppSecret，在微信开放平台提交应用审核通过后获得
     code    是    填写第一步获取的code参数
     grant_type    是    填authorization_code
     */
    NSString *url =[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code",@"wx2d157e5d72319a6f",@"2b2207c7bade175d182afc9185a8240c",code];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSURL *zoneUrl = [NSURL URLWithString:url];
        NSString *zoneStr = [NSString stringWithContentsOfURL:zoneUrl encoding:NSUTF8StringEncoding error:nil];
        NSData *data1 = [zoneStr dataUsingEncoding:NSUTF8StringEncoding];
        
        if (!data1) {
            [MBProgressHUD showError:@"微信授权失败" toView:nil];
            return ;
        }
        
        // 授权成功，获取token、openID字典
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data1 options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"token、openID字典===%@",dic);
        NSString *access_token = dic[@"access_token"];
        NSString *openid= dic[@"openid"];
        
        //         获取微信用户信息
        [self getUserInfoWithAccessToken:access_token WithOpenid:openid];
        
    });
}

-(void)getUserInfoWithAccessToken:(NSString *)access_token WithOpenid:(NSString *)openid
{
    NSString *url =[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@",access_token,openid];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSURL *zoneUrl = [NSURL URLWithString:url];
        NSString *zoneStr = [NSString stringWithContentsOfURL:zoneUrl encoding:NSUTF8StringEncoding error:nil];
        NSData *data = [zoneStr dataUsingEncoding:NSUTF8StringEncoding];
        dispatch_async(dispatch_get_main_queue(), ^{
            
            // 获取用户信息失败
            if (!data) {
                [MBProgressHUD showError:@"微信授权失败" toView:nil];
                return ;
            }
            
            // 获取用户信息字典
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            //用户信息中没有access_token 我将其添加在字典中
            [dic setValue:access_token forKey:@"token"];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"wxLogin" object:dic];
            
        });
        
    });
    
}
-(void)needQQLogin{
    //appkey:81c79b714ed87b5cd7b9986cecadb401
    if ([TencentOAuth iphoneQQInstalled]) {
        NSArray *permissions = [NSArray arrayWithObjects:kOPEN_PERMISSION_GET_INFO, kOPEN_PERMISSION_GET_USER_INFO, kOPEN_PERMISSION_GET_SIMPLE_USER_INFO, nil];
        [_oauth authorize:permissions];
    }
}

//登录成功：
- (void)tencentDidLogin
{
    if (_oauth.accessToken.length > 0) {
        // 获取用户信息
        [_oauth getUserInfo];
        
    } else {
        NSLog(@"登录不成功 没有获取accesstoken");
    }
}

//非网络错误导致登录失败：
- (void)tencentDidNotLogin:(BOOL)cancelled {
    if (cancelled) {
        NSLog(@"用户取消登录");
    } else {
        NSLog(@"登录失败");
    }
}

- (void)getUserInfoResponse:(APIResponse *)response {
    if (response && response.retCode == URLREQUEST_SUCCEED) {
        NSDictionary *userInfo = [response jsonResponse];
        NSString *nickName = userInfo[@"nickname"];
        NSString *avatar = userInfo[@"figureurl_2"];
        NSDictionary *dic =@{
            @"openid": _oauth.openId,
            @"headimgurl": avatar,
            @"nickname": nickName
        };
        [[NSNotificationCenter defaultCenter] postNotificationName:@"qqLogin" object:dic];

    } else {
        NSLog(@"QQ auth fail ,getUserInfoResponse:%d", response.detailRetCode);
    }
}

-(BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController{
    if ([User isGuest]) {
        CYLTabBarController *tabbar = (CYLTabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
        NSInteger index = [tabbar.viewControllers indexOfObject:viewController];
        if (index == 2) {
            LoginViewController *vc = [LoginViewController new];
            BaseNavigationController *nav = [[BaseNavigationController alloc] initWithRootViewController:vc];
            nav.modalPresentationStyle = UIModalPresentationOverFullScreen;
            [tabBarController presentViewController:nav animated:YES completion:nil];
            return NO;
        }
    }
    return YES;
}
@end
